package com.auxgroup.hr.front.commons.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * FTP上传文件工具类
 * @author lv-PC
 *
 */
@Component
@Scope(value="singleton")
public class FtpFileUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FtpFileUtil.class);

    @Value("${auxgroup.hr.ftp.address}")
    private  String FTP_ADDRESS;//ftp服务器ip地址
    
    @Value("${auxgroup.hr.ftp.port}")
    private  Integer FTP_PORT;//端口号
   
    @Value("${auxgroup.hr.ftp.username}")
    private  String FTP_USERNAME; //用户名
    
    @Value("${auxgroup.hr.ftp.password}")
    private  String FTP_PASSWORD;//密码
    
    public FTPClient ftpClient = new FTPClient();

    public  Boolean initFtpClient() {
        try {
            logger.info("start connect ftp address:{},port:{},username:{},password:{}",FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD);
            ftpClient.connect(FTP_ADDRESS, FTP_PORT); //连接ftp服务器
            ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
                logger.info("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
                return false;
            } else {  
                logger.info("FTP连接成功。");  
            }  
        }catch (MalformedURLException e) { 
        	 logger.error("connect ftp failed..host:{},port:{}",FTP_ADDRESS,FTP_PORT,e); 
        	 return false;
        }catch (IOException e) { 
        	 logger.error("connect ftp failed..host:{},port:{}",FTP_ADDRESS,FTP_PORT,e); 
        	 return false;
        } 
        return true;
    }
    
    
    /**
     * 获取一个新的ftp连接
     * @return
     */
    public FTPClient getNewFtpClient(){
    	FTPClient newftp = new FTPClient();
    	try {
            logger.info("start connect ftp address:{},port:{},username:{},password:{}",FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD);
            newftp.connect(FTP_ADDRESS, FTP_PORT); //连接ftp服务器
            newftp.login(FTP_USERNAME, FTP_PASSWORD);
            if (!FTPReply.isPositiveCompletion(newftp.getReplyCode())) {  
                logger.info("未连接到FTP，用户名或密码错误。");
                newftp.disconnect();
                return null;
            } else {  
                logger.info("FTP连接成功。");  
            }  
        }catch (MalformedURLException e) { 
        	 logger.error("connect ftp failed..host:{},port:{}",FTP_ADDRESS,FTP_PORT,e); 
        	 return null;
        }catch (IOException e) { 
        	 logger.error("connect ftp failed..host:{},port:{}",FTP_ADDRESS,FTP_PORT,e); 
        	 return null;
        } 
        return newftp;
    }
    
    /**
     * 上传文件
     * @param path ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param inputStream 输入文件流 
     * @return
     */
    public Boolean uploadFile(String path, String fileName,InputStream inputStream){
        boolean flag = false;
        try{
        	logger.info("start upload file path={},fileName={}",path,fileName);
            if(!initFtpClient()){
                return false;
            }
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            if(!ftpClient.changeWorkingDirectory(path)){
            	ftpClient.makeDirectory(path);
            	ftpClient.changeWorkingDirectory(path);
            }
            flag = ftpClient.storeFile(fileName, inputStream);
            logger.info("ftp upload success");
        }catch (Exception e) {
        	logger.error("ftp upload faild:",e);
        }finally{
        	if(ftpClient.isConnected()){ 
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                	logger.error("ftpclient disconnect faild:",e);
                }
            } 
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                	logger.error("inputStream close faild:",e);
                } 
            } 
        }
        return flag;
    }
    

    /**
     * 判断ftp服务器文件是否存在    
     * @param path
     * @return
     * @throws IOException
     */
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        if(!initFtpClient()){
            return false;
        }
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }
    
    /** * 下载文件 * 
    * @param pathname FTP服务器文件目录 * 
    * @param filename 文件名称 * 
    * @param localpath 下载后的文件路径 * 
    * @return */
    public  boolean downloadFile(String pathname, String filename, String localpath,FTPClient client){ 
        boolean flag = false; 
        OutputStream os=null;
        try { 
        	logger.info("ftp download start:pathname={},filename={},localpath={}",pathname, filename,localpath);
            File localFile = new File(localpath + "/" + filename); 
            if(!localFile.exists()){
		   		 if(!localFile.getParentFile().exists()){
		   			localFile.getParentFile().mkdirs();
		   		 }else{
		   			localFile.createNewFile();
		   		 }
		   		if(client==null){
	                return false;
	            }
		   		//切换FTP目录 
		   		client.changeWorkingDirectory(pathname); 
		   		os = new FileOutputStream(localFile);
		   		flag = client.retrieveFile(filename, os);
		   		client.logout(); 
		   		if(flag){
	            	logger.info("ftp download success");
	            	return flag;
	            }; 
            }
            logger.info("file exist!");
            flag = true;
        } catch (Exception e) { 
        	logger.error("ftp download faild",e);
        } finally{ 
            if(client.isConnected()){ 
                try{
                	client.disconnect();
                }catch(IOException e){
                	logger.error("ftpclient disconnect faild:",e);
                }
            } 
            if(null != os){
                try {
                    os.close();
                } catch (IOException e) {
                	logger.error("os close faild:",e);
                } 
            } 
        } 
        return flag; 
    }
    
    
    /** * 下载文件 * 
     * @param pathname FTP服务器文件目录 * 
     * @param filename 文件名称 * 
     * @param localpath 下载后的文件路径 * 
     * @return */
     public  boolean downloadFile(String pathname, String filename, String localpath){
    	 //文件存在不继续
    	 File localFile = new File(localpath + "/" + filename); 
         if(localFile.exists()){
        	 logger.info("file exist!");
        	 return true;
         }
         //初始化失败不继续
    	 if(!initFtpClient()){
    		 return false;
    	 }
    	 return downloadFile(pathname,filename,localpath,this.ftpClient);
     }
    
    /**
     * 删除文件 
     * @param pathname FTP服务器保存目录 * 
     * @param filename 要删除的文件名称 * 
     * @return 
    */ 
    public boolean deleteFile(String pathname, String filename){ 
        boolean flag = false; 
        try { 
        	 logger.info("ftp deleteFile start");
        	 if(!initFtpClient()){
                 return false;
             }
            //切换FTP目录 
            ftpClient.changeWorkingDirectory(pathname); 
            ftpClient.dele(filename); 
            ftpClient.logout();
            flag = true; 
            logger.info("ftp deleteFile success");
        } catch (Exception e) { 
        	logger.info("ftp deleteFile faild",e);
        } finally {
            if(ftpClient.isConnected()){ 
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                	logger.error("ftpclient disconnect faild:",e);
                }
            } 
        }
        return flag; 
    }
    
    
    /**
     * 删除文件 
     * @param pathname FTP服务器保存目录 * 
     * @param filename[] 要删除的文件名称数组 * 
     * @return 
    */ 
    public boolean deleteFile(String pathname, String[] filename){ 
        boolean flag = false; 
        try { 
        	 logger.info("ftp deleteFile start");
        	 if(!initFtpClient()){
                 return false;
             }
            //切换FTP目录 
            ftpClient.changeWorkingDirectory(pathname); 
            for (int i = 0; i < filename.length; i++) {
            	 ftpClient.dele(filename[i]); 
			}
            ftpClient.logout();
            flag = true; 
            logger.info("ftp deleteFile success");
        } catch (Exception e) { 
        	logger.info("ftp deleteFile faild",e);
        } finally {
            if(ftpClient.isConnected()){ 
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                	logger.error("ftpclient disconnect faild:",e);
                }
            } 
        }
        return flag; 
    }
}